package cn.itcast.server;

import cn.itcast.handler.ChatMessageServerHandler;
import cn.itcast.handler.GroupCreateServerMessageHandler;
import cn.itcast.message.GroupCreateRequestMessage;
import cn.itcast.message.LoginRequestMessage;
import cn.itcast.message.LoginResponseMessage;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProcotolFrameDecoder;
import cn.itcast.server.service.UserService;
import cn.itcast.server.service.UserServiceFactory;
import cn.itcast.server.session.Group;
import cn.itcast.server.session.Session;
import cn.itcast.server.session.SessionFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServer {
    public static void main(String[] args) {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        ChatMessageServerHandler CHAT_REQUEST_HANDLER = new ChatMessageServerHandler();
        GroupCreateServerMessageHandler GROUP_CREATE_HANDLER = new GroupCreateServerMessageHandler();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<LoginRequestMessage>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage loginRequestMessage) throws Exception {
                            UserService userService = UserServiceFactory.getUserService();
                            Session session = SessionFactory.getSession();
                            boolean login = userService.login(loginRequestMessage.getUsername(), loginRequestMessage.getPassword());
                            if (login) {
                                session.bind(ch, loginRequestMessage.getUsername());
                                LoginResponseMessage msg = new LoginResponseMessage(true, "登陆成功");
                                ch.writeAndFlush(msg);
                            }else{
                                LoginResponseMessage msg = new LoginResponseMessage(false, "用户名或密码错误");
                                ch.writeAndFlush(msg);
                            }
                        }
                    });
                    ch.pipeline().addLast(CHAT_REQUEST_HANDLER);
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                    super.exceptionCaught(ctx, cause);
                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
